package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"server/internal/model"
	"server/internal/router/manager"
	"server/pkg/app"
	"server/pkg/errcode"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			token string
			ecode = errcode.Success
		)

		if s, exist := c.GetQuery("token"); exist {
			token = s
		} else {
			token = c.GetHeader("token")
		}

		//token 为用户登录后生成的token,api_token为用户自己生成的token
		api_token := c.GetHeader("api_token")
		if token == "" {
			if api_token == "" {
				ecode = errcode.InvalidParams
			} else {
				user := model.QueryToken(api_token)
				if len(user.Name) == 0 {
					ecode = errcode.ApiTokenError
				} else {
					c.Set("username", user.Name)
				}
			}
		} else {
			claims, err := app.ParseToken(token)
			if err != nil {
				ecode = errcode.UnauthorizedTokenTimeout
			} else {
				if len(claims.StandardClaims.Issuer) != 0 {
					c.Set("username", claims.StandardClaims.Issuer)
				} else {
					ecode = errcode.UnauthorizedTokenTimeout
				}
			}

			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					ecode = errcode.UnauthorizedTokenTimeout
				}
			}
		}

		if ecode != errcode.Success {
			app.ToErrorResponse(c, ecode)
			c.Abort()
			return
		}

		// 超级管理员有所有操作执行权限
		username := c.GetString("username")
		if AuthorityCheck(c, username) {
			c.Next()
		} else {
			ecode = errcode.NoAuthoriry
			app.ToErrorResponse(c, ecode)
			c.Abort()
			return
		}
	}
}

// 权限管理
func AuthorityCheck(c *gin.Context, username string) bool {
	if username == "admin" {
		return true
	}
	// 获取用户角色（实际应从数据库查询）
	userRole := manager.GetUserRole(username)
	if userRole == "" {
		return false
	}
	// 获取请求信息
	path := c.Request.URL.Path
	method := c.Request.Method

	// 执行权限验证
	//policies, err := manager.Enforcer.GetPolicy()
	// 开启调试日志
	manager.Enforcer.EnableLog(true)

	ok, err := manager.Enforcer.Enforce(userRole, path, method)
	if err != nil {
		return false
	}
	if !ok {
		return false
	}
	return true
}
